package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.core.OutUrlConstant;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.goods.NEWIKGAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author sdq
 * @Date 2022/8/31 22:28
 */
@Slf4j
@Service
public class NEWKGAPIImpl implements NEWIKGAPI {
    @Resource
    private CommonApi commonApi;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private ArtRecMapper artRecMapper;

    private static String KGURL = null;

    private Map<String,Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,SalePartner salePartner){

        KGURL = salePartner.getOther();
        Map<String,Object> params = new TreeMap<>();
        params.put("game_code",goodsInfoAndAttrValueDto.getId().toString());//账号编号
        params.put("game_type","9");//游戏类型ID（固定9）
        //1王者荣耀; 2原神; 3和平精英;4吃鸡
        String atta = "";
        if("王者荣耀".equals(goodsInfoAndAttrValueDto.getGameName())){
            params.put("game_id","10");//游戏名称ID（王者10，吃鸡11）
            String data = JSONObject.parseObject(getAtta(10)).getString("data");
            JSONArray jsonArray1 = JSONArray.parseArray(MapUntils.unicodeToString(data));
            String pfIds = "";
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF9());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF10());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF11());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF12());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF15());
            List<GameAttribute> gameAttributesss = getGameAttributs(pfIds);
            for(GameAttribute gameAttribute1 : gameAttributesss) {
                if(gameAttribute1.getFieldName().equals("孙策-末日机甲")){
                    gameAttribute1.setFieldName("末日机甲策");
                }
                if(gameAttribute1.getFieldName().equals("孙尚香-末日机甲")){
                    gameAttribute1.setFieldName("末日机甲女");
                }
                if(gameAttribute1.getFieldName().equals("吕布-末日机甲")){
                    gameAttribute1.setFieldName("末日机甲男");
                }
                if(gameAttribute1.getFieldName().equals("孙尚香-时之恋人")){
                    gameAttribute1.setFieldName("时之恋人女");
                }
                if(gameAttribute1.getFieldName().equals("刘备-时之恋人")){
                    gameAttribute1.setFieldName("时之恋人男");
                }
                if(gameAttribute1.getFieldName().equals("兰陵王-默契交锋")){
                    gameAttribute1.setFieldName("默契交锋男");
                }
                if(gameAttribute1.getFieldName().equals("刘备-时之恋人")){
                    gameAttribute1.setFieldName("默契交锋女");
                }
                if(gameAttribute1.getFieldName().equals("项羽-霸王别姬")){
                    gameAttribute1.setFieldName("霸王别姬男");
                }
                if(gameAttribute1.getFieldName().equals("虞姬-霸王别姬")){
                    gameAttribute1.setFieldName("霸王别姬女");
                }
                if(gameAttribute1.getFieldName().equals("项羽-无限倾心")){
                    gameAttribute1.setFieldName("无限倾心男");
                }
                if(gameAttribute1.getFieldName().equals("虞姬-无限倾心")){
                    gameAttribute1.setFieldName("无限倾心女");
                }
                if(gameAttribute1.getFieldName().equals("瑶-时之祈愿")){
                    gameAttribute1.setFieldName("时之祈愿女");
                }
                if(gameAttribute1.getFieldName().equals("云中君-时之祈愿")){
                    gameAttribute1.setFieldName("时之祈愿男");
                }
                if(gameAttribute1.getFieldName().equals("小乔-音你心动")){
                    gameAttribute1.setFieldName("音你心动女");
                }
                if(gameAttribute1.getFieldName().equals("周瑜-音你心动")){
                    gameAttribute1.setFieldName("音你心动男");
                }
                if(gameAttribute1.getFieldName().equals("大乔-猫狗日记")){
                    gameAttribute1.setFieldName("猫狗日记女");
                }
                if(gameAttribute1.getFieldName().equals("孙策-猫狗日记")){
                    gameAttribute1.setFieldName("猫狗日记男");
                }
                if(gameAttribute1.getFieldName().equals("安琪拉-时之奇旅")){
                    gameAttribute1.setFieldName("时之奇旅安琪");
                }
                if(gameAttribute1.getFieldName().equals("妲己-时之奇旅")){
                    gameAttribute1.setFieldName("时之奇旅妲己");
                }
                for (Object o : jsonArray1) {
                    if (gameAttribute1.getFieldName().replace("-","").replace("·","").contains(JSONObject.parseObject(o.toString()).getString("brandname"))) {
                        atta +=","+JSONObject.parseObject(o.toString()).getString("brandname");
                    }
                }
            }
        }else if("和平精英".equals(goodsInfoAndAttrValueDto.getGameName())){
            params.put("game_id","11");//游戏名称ID（王者10，吃鸡11）
            String response = getAtta(11);
            String data = JSONObject.parseObject(response).getString("data");
            JSONArray jsonArray1 = JSONArray.parseArray(MapUntils.unicodeToString(data));
            String pfIds = "";
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF1());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF2());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF3());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF4());
            pfIds = reIds(pfIds, goodsInfoAndAttrValueDto.getF5());
            List<GameAttribute> gameAttributesss = getGameAttributs(pfIds);
            for(GameAttribute gameAttribute1 : gameAttributesss){
                for(Object o : jsonArray1){
                    if(gameAttribute1.getFieldName().contains(JSONObject.parseObject(o.toString()).getString("brandname"))||JSONObject.parseObject(o.toString()).getString("brandname").contains(gameAttribute1.getFieldName())){
                        atta +=","+JSONObject.parseObject(o.toString()).getString("brandname");
                    }
                }
            }
        }else{
            throw new GlobalException("暂不支持此游戏");
        }
        params.put("account_number",goodsInfoAndAttrValueDto.getId().toString());
        GameAttribute gameAttribute = null;
        if (Objects.equals("王者荣耀",goodsInfoAndAttrValueDto.getGameName())){
            params.put("camp_id",goodsInfoAndAttrValueDto.getF17()==null||goodsInfoAndAttrValueDto.getF17().equals("")?"123":goodsInfoAndAttrValueDto.getF17());//营地号
            params.put("hero_num",null == goodsInfoAndAttrValueDto.getF7()?"0":goodsInfoAndAttrValueDto.getF7().toString());//英雄数量/套装数量
            params.put("skin_num",null == goodsInfoAndAttrValueDto.getF8()?"0":goodsInfoAndAttrValueDto.getF8().toString());//皮肤数量/枪皮数量
            params.put("inscription_num",goodsInfoAndAttrValueDto.getF13()==null||goodsInfoAndAttrValueDto.getF13().equals("")?"1":goodsInfoAndAttrValueDto.getF13());//五级铭文数量/载具数量
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF16()));
        }else {
            params.put("camp_id",goodsInfoAndAttrValueDto.getF13()==null||goodsInfoAndAttrValueDto.getF13().equals("")?"123":goodsInfoAndAttrValueDto.getF13());//营地号
            params.put("hero_num",null == goodsInfoAndAttrValueDto.getF8()?"0":goodsInfoAndAttrValueDto.getF8().toString());//英雄数量/套装数量
            params.put("skin_num",null == goodsInfoAndAttrValueDto.getF9()?"0":goodsInfoAndAttrValueDto.getF9().toString());//皮肤数量/枪皮数量
            params.put("inscription_num",goodsInfoAndAttrValueDto.getF7()==null||goodsInfoAndAttrValueDto.getF7().equals("")?"1":goodsInfoAndAttrValueDto.getF7());//五级铭文数量/载具数量
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
        }
        params.put("title","【"+ goodsInfoAndAttrValueDto.getId() + "】  "+ gameAttribute.getFieldName() + "  " + goodsInfoAndAttrValueDto.getDes());
        params.put("game_img",goodsInfoAndAttrValueDto.getTitleImg()==null||goodsInfoAndAttrValueDto.getTitleImg().equals("")? LCConstant.defaultImg:goodsInfoAndAttrValueDto.getTitleImg());
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        if(!CollectionUtils.isEmpty(infoImgs)){
            params.put("images",infoImgs.stream().map(GoodsInfoImg::getImgUrl).collect(Collectors.joining(",")));
        }
        if(goodsInfoAndAttrValueDto.getCarrierName().endsWith("Q")){
            params.put("game_account_type","1");//账号类型（1 QQ 2 微信）
        }else{
            params.put("game_account_type","2");//账号类型（1 QQ 2 微信）
        }
        if(goodsInfoAndAttrValueDto.getSystemName().startsWith("安卓")){
            params.put("is_system","1");//操作系统（1 安卓 2 苹果）
        }else{
            params.put("is_system","2");//操作系统（1 安卓 2 苹果）
        }
        params.put("game_region",goodsInfoAndAttrValueDto.getGroupName()==null||goodsInfoAndAttrValueDto.getGroupName().equals("")?"1":goodsInfoAndAttrValueDto.getGroupName());//游戏大区
        BigDecimal bigDecimal = commonApi.addPrice(goodsInfoAndAttrValueDto.getPrice(), salePartner.getSeleep());
        commonApi.setPrice(bigDecimal,goodsInfoAndAttrValueDto.getId(),salePartner);
        params.put("game_sell_price",bigDecimal);//销售价
        if(gameAttribute.getFieldName().contains("无二次")) {
            params.put("ercixiugai", "N");
        }
        if(gameAttribute.getFieldName().contains("可二次实名")) {
            params.put("ercixiugai", "Y");
        }
        if(gameAttribute.getFieldName().contains("包人脸")) {
            params.put("ercixiugai", "B");
        }
        if(gameAttribute.getFieldName().contains("已删实名")) {
            params.put("ercixiugai", "C");
        }
        if(StringUtils.isNotEmpty(atta)) {
            params.put("attrData", atta.substring(1));
        }else{
            params.put("attrData", "无");
        }
        //以上 计算key
        String str = MapUntils.getCover(params) + "key=" +salePartner.getSaleKey();
        System.out.println(str);
        String sign = DigestUtils.md5Hex(str).toUpperCase();
        params.put("signKey",sign);
        String level = "8073";
        if(goodsInfoAndAttrValueDto.getGameName().contains("王者荣耀")) {
            GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF2()));
            if(gameAttribute1.getFieldName().contains("无")||gameAttribute1.getFieldName().contains("V1")||gameAttribute1.getFieldName().contains("V2")||gameAttribute1.getFieldName().contains("V3")){
                level = "8070";
            }else if(gameAttribute1.getFieldName().contains("V4")){
                level = "8071";
            }else if(gameAttribute1.getFieldName().contains("V5")){
                level = "8072";
            }else{
                level = "8073";
            }
        }
        params.put("noble_points","1");
        params.put("level",level);
        params.put("is_paiwei", "7697");
        params.put("userId",salePartner.getTwoOther());
        return params;
    }
    private List<GameAttribute> getGameAttributs(String ids) {
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }
    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }
    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,  SalePartner salePartner) {
        try{
            Map<String, Object> result = new HashMap<>();
            Map<String, Object> params = params(goodsInfoAndAttrValueDto,salePartner);
            params.put("pg","apiAddGame");
            String paramsStr = JSONObject.toJSONString(params);
            log.info("凯哥新增请求参数={}",paramsStr);
            String response = "";
            if (Objects.isNull(KGURL)){
                response = HttpUtils.doPostForm(OutUrlConstant.KGURL, params, null);
            }else {
                response = HttpUtils.doPostForm(KGURL, params, null);
            }

            log.info("凯哥新增返回参数={}",MapUntils.unicodeToString(response));
            JSONObject resultJson = JSONObject.parseObject(response);
            String msg = resultJson.getString("msg");
            msg = MapUntils.unicodeToString(msg);
            if (!(1 == resultJson.getInteger("code"))){
                result.put("code",500);
            }else {
                result.put("code",200);
                ArtRec artRecreq = new ArtRec();
                artRecreq.setConfig(salePartner.getId());
                artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
                if(artRecs.size()>0) {
                    artRecs.get(0).setOutid(msg.replace("添加成功,账号ID：",""));
                    artRecMapper.updateArtRec(artRecs.get(0));
                }else{
                    artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                    artRecreq.setCreateId(goodsInfoAndAttrValueDto.getCreateId());
                    artRecreq.setType(LCConstant.interAdd);
                    artRecreq.setConfig(salePartner.getId());
                    artRecreq.setSaleCode(salePartner.getSaleName());
                    artRecreq.setOutid(msg.replace("添加成功,账号ID：",""));
                    artRecMapper.insertArtRec(artRecreq);
                }
            }
            result.put("req",JSONObject.toJSONString(params));
            result.put("res",MapUntils.unicodeToString(response));
            result.put("msg",msg);
            return AjaxResult.success(result);
        }catch (Exception e){
            throw new GlobalException(e.getMessage());
        }
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,  SalePartner salePartner) {
        try{
            Map<String, Object> result = new HashMap<>();
            Map<String, Object> params = params(goodsInfoAndAttrValueDto,salePartner);
            params.put("pg","apiUpdGame");
            String paramsStr = JSONObject.toJSONString(params);
            log.info("凯哥修改请求参数={}",paramsStr);
            String response = "";
            if (Objects.isNull(KGURL)){
                response = HttpUtils.doPostForm(OutUrlConstant.KGURL, params, null);
            }else {
                response = HttpUtils.doPostForm(KGURL, params, null);
            }

            log.info("凯哥修改返回参数={}",MapUntils.unicodeToString(response));
            JSONObject resultJson = JSONObject.parseObject(response);
            String msg = resultJson.getString("msg");
            msg = MapUntils.unicodeToString(msg);
            if (!(1 == resultJson.getInteger("code"))){
                result.put("code",500);
            }else {
                result.put("code",200);
            }
            result.put("req",JSONObject.toJSONString(params));
            result.put("res",response);
            result.put("msg",msg);
            return AjaxResult.success(result);
        }catch (Exception e){
            throw new GlobalException(e.getMessage());
        }
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner sa) {
        try{
            KGURL = sa.getOther();
            Map<String, Object> result = new HashMap<>();
            Map<String, String> params = new HashMap<>();
            params.put("pg","apiDelGame");
            params.put("userId",sa.getTwoOther());
            params.put("game_code",goodsInfoAndAttrValueDto.getId().toString());
            String sign = DigestUtils.md5Hex("game_code="+ params.get("game_code")+ "&key=" +sa.getSaleKey()).toUpperCase();
            params.put("signKey",sign);
            String paramsStr = "pg=apiDelGame&userId="+ sa.getTwoOther() + "&game_code="+goodsInfoAndAttrValueDto.getId().toString()+"&signKey="+sign;
            log.info("凯哥删除请求参数={}",paramsStr);
            String response = "";
            if (Objects.isNull(KGURL)){
                response = HttpUtils.doPostForm(OutUrlConstant.KGURL, params,null);
            }else {
                response = HttpUtils.doPostForm(KGURL, params,null);
            }

            log.info("凯哥删除返回参数={}",MapUntils.unicodeToString(response));
            JSONObject resultJson = JSONObject.parseObject(response);
            String msg = resultJson.getString("msg");
            msg = MapUntils.unicodeToString(msg);
            if (!(1 == resultJson.getInteger("code"))){
                result.put("code",500);
            }else {
                result.put("code",200);
                ArtRec artRecreq = new ArtRec();
                artRecreq.setConfig(sa.getId());
                artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
                if(artRecs.size()>0) {
                    artRecMapper.deleteArtRecById(artRecs.get(0).getId());
                }
            }
            result.put("req",JSONObject.toJSONString(params));
            result.put("res",MapUntils.unicodeToString(response));
            result.put("msg",msg);
            return AjaxResult.success(result);
        }catch (Exception e){
            throw new GlobalException(e.getMessage());
        }
    }

    public static String getCover(Map<String,Object> params){
        StringBuffer resut = new StringBuffer();
        for (String key : params.keySet()) {
            if(params.get(key) instanceof String && StringUtils.isNotEmpty((String)params.get(key))){
                resut.append(key+"="+params.get(key)+"&");
            }
            if(params.get(key) instanceof Boolean){
                resut.append(key+"="+params.get(key)+"&");
            }
            if(params.get(key) instanceof Long){
                resut.append(key+"="+params.get(key)+"&");
            }
            if(params.get(key) instanceof Integer && null != params.get(key)){
                resut.append(key+"="+params.get(key)+"&");
            }
        }
        return resut.toString();
    }

    public static void main(String[] args) {
//-------------------新增-------------------------
//        Map<String,Object> params = new TreeMap<>();
//        params.put("game_code","test");
//        params.put("game_type","9");//游戏类型ID（固定9）
//        params.put("game_id","10");//游戏名称ID（王者10，吃鸡11）
//        params.put("camp_id","198");//营地号
//        params.put("account_number","1");
//        params.put("hero_num","200");//英雄数量/套装数量
//        params.put("skin_num","100");//皮肤数量/枪皮数量
//        params.put("title","title");
//        params.put("images","1");
//        params.put("game_img","1");
//        params.put("game_account_type","1");//账号类型（1 QQ 2 微信）
//        params.put("is_system","1");//操作系统（1 安卓 2 苹果）
//        params.put("game_region","1");//游戏大区
//        params.put("inscription_num","1");//五级铭文数量/载具数量
//        params.put("game_sell_price","188");//销售价
//
//        //以上 计算key
//        String str = getCover(params) + "key="+"n5je6zli5425c24yz60js59lfx236o51231" ;
//        System.out.println("signStr : "+str);
//        String sign = DigestUtils.md5Hex(str).toUpperCase();
//        System.out.println("sign: "+sign);
//        params.put("signKey",sign);
//
//        params.put("pg","apiAddGame");
//        params.put("userId","5");
//
//
//        System.out.println(JSONObject.toJSONString(params));
//        String baseUrl = "http://www.kaigewangyou.com/api/api.php";
//        String response = HttpUtils.doPostForm(baseUrl, params, null);
//        System.out.println(response);
//        JSONObject resultJson = JSONObject.parseObject(response);
//        String msg = resultJson.getString("msg");
//        System.out.println(msg);

        //------修改

//        params.put("game_code","test");
//        params.put("game_type","9");//游戏类型ID（固定9）
//        params.put("camp_id","198");//营地号
//        params.put("account_number","1");
//        params.put("hero_num","200");//英雄数量/套装数量
//        params.put("skin_num","100");//皮肤数量/枪皮数量
//        params.put("title","title");
//        params.put("images","http://oss.p74.cn/5/2021/04/09/1617973327139.jpg");
//        params.put("game_img","http://oss.p74.cn/5/2021/04/09/1617973327139.jpg");
//        params.put("game_account_type","1");//账号类型（1 QQ 2 微信）
//        params.put("is_system","1");//操作系统（1 安卓 2 苹果）
//        params.put("game_region","1");//游戏大区
//        params.put("inscription_num","1");//五级铭文数量/载具数量
//        params.put("game_sell_price","188");//销售价
//        params.put("game_id","10");//游戏名称ID（王者10，吃鸡11）
//        //以上 计算key
//        String str = getCover(params) + "key=" + "n5je6zli5425c24yz60js59lfx236o51231";
//        String sign = DigestUtils.md5Hex(str).toUpperCase();
//        params.put("signKey",sign);
//
//        params.put("userId","5");
//        params.put("pg","apiUpdGame");
//
//        System.out.println(JSONObject.toJSONString(params));
//        Map<String,Object> params = new TreeMap<>();
//        String baseUrl = "http://mh.kaigewangyou.com/api/api.php?pg=getGameId";
//        params.put("gameId",10);
        String response = getAtta(11);
        System.out.println(MapUntils.unicodeToString(response));

    }

    public static String getAtta(Integer gameId){
        Map<String,Object> params = new TreeMap<>();
        String baseUrl = "http://mh.kaigewangyou.com/api/api.php?pg=getGameId";
        params.put("gameId",gameId);
        String response = HttpUtils.doPostForm(baseUrl, params, null);
        return response;
    }
}
